//
//  BedDetailTableViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 08/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "BedDetailTableViewController.h"
#import "Plant.h"
#import "UITableView+TableSectionHeaderText.h"
#import "Bed+DoesBedContainIncompatiblePlant.h"
#import "PlotIncompatibilty.h"
#import "PlotIncompatibilty+CRUD.h"
#import "Bed+CRUD.h"
#import "Plot.h"
#import "UILabel+TextFont.h"
#import "SuggestedCompanionsTableViewController.h"

@interface BedDetailTableViewController()

@property (nonatomic, strong) NSMutableArray *plantArray;
@property (nonatomic, strong) NSMutableArray *incompatibles;
@property (nonatomic, strong) PlotIncompatibilty *selectedIncompatible;

@end

@implementation BedDetailTableViewController

@synthesize bed = _bed;
@synthesize plantCell = _plantCell;
@synthesize plantArray = _plantArray;
@synthesize incompatibles = _incompatibles;
@synthesize selectedIncompatible = _selectedIncompatible;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
    
    //Instantiate an array that hold the list of incompatibilities
    self.incompatibles = [[NSMutableArray alloc] init];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.bed = [Bed selectBedWithName:self.bed.name inPlot:self.bed.plot.name withContext:self.bed.managedObjectContext];
    self.plantArray = [NSMutableArray arrayWithArray:[self.bed.plants allObjects]];
    //reload the data in the table each time the view is displayed to cater for new additions to the bed
    [self.tableView reloadData];
    self.title = self.bed.name;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1){
        return [self.bed.plants count];
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return 80;
    }else if(indexPath.section == 1){
        return 57;
    }
    return 44;
}

-(UITableViewCell *)buildNameAndDimensionCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"dimensionsCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    //Check what unit of measurement is configured and change the text on screen accordingly
    NSString *unitToMeasure;
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if([prefs boolForKey:@"metric"]){
        unitToMeasure = @"m";
    }else {
        unitToMeasure = @"ft";
    }
    UILabel *dimensionsLabel = (UILabel *)[cell viewWithTag:4];
    [dimensionsLabel setSketchBlockFont];
    UILabel *dimensionsValueLabel = (UILabel *)[cell viewWithTag:2];
    dimensionsValueLabel.text = [[[[[self.bed.size1 stringValue] stringByAppendingString:unitToMeasure] stringByAppendingString:@" X "] stringByAppendingString:[self.bed.size2 stringValue]] stringByAppendingString:unitToMeasure];
    dimensionsValueLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    
    UILabel *viewCompanionsLabel = (UILabel *)[cell viewWithTag:3];
    [viewCompanionsLabel setMVBoliFont];
    
    //Set transparent background on cell with no border
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
    
}


-(UITableViewCell *)buildPlantCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"plantCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"PlantListCell" owner:self options:nil];
        cell = _plantCell;
        self.plantCell = nil;
    }
    
    Plant *plant = [self.plantArray objectAtIndex:indexPath.row];
    
    UIImageView *thumbnail = (UIImageView *)[cell viewWithTag:1];
    thumbnail.image = [UIImage imageNamed:[plant.name stringByAppendingString:@"_S"]];
    
    UILabel *label = (UILabel *)[cell viewWithTag:2];
    label.text = plant.name;
    [label setSketchBlockFont];
    
    PlotIncompatibilty *incomp = [self.bed getIncompatibility:plant];
    
    //If an incompatibility exists and the user wants to be alerted, then show a little bug image on the table cell
    if(incomp != nil && [incomp.alertUser isEqualToNumber:[NSNumber numberWithBool:YES]]){
        CGPoint cellOrigin = cell.frame.origin;
        UIButton *bugButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [bugButton setFrame:CGRectMake(cellOrigin.x + 235, cellOrigin.y + 8, 40, 40)];
        [bugButton setBackgroundImage:[UIImage imageNamed:@"bug_icon.png"] forState:UIControlStateNormal];
        [bugButton setBackgroundImage:[UIImage imageNamed:@"bug_icon_down.png"] forState:UIControlStateHighlighted];
        bugButton.tag = [self.incompatibles count] + 32;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bugTapped:)];
        [self.incompatibles addObject:incomp];
        [bugButton addGestureRecognizer:tapGesture]; 
        [cell addSubview:bugButton];
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell setBackgroundView:[[UIView alloc] initWithFrame:CGRectZero]];
    return cell;
}



-(UITableViewCell *)buildDeleteButtonCellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"deleteButtonCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    
    UIButton *deleteButton = (UIButton *)[cell viewWithTag:2];
    [deleteButton setBackgroundImage:[[UIImage imageNamed:@"delete_button.png"]
                                      stretchableImageWithLeftCapWidth:8.0f
                                      topCapHeight:0.0f]
                            forState:UIControlStateNormal];
    
    [deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    deleteButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    deleteButton.titleLabel.shadowColor = [UIColor lightGrayColor];
    deleteButton.titleLabel.shadowOffset = CGSizeMake(0, -1);
    
    //Set the delete button to hidden until we are in edit mode
    [deleteButton setHidden:YES];
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return [self buildNameAndDimensionCellsForTableView:tableView atIndexPath:indexPath];
    }else if(indexPath.section == 1){
        return [self buildPlantCellsForTableView:tableView atIndexPath:indexPath];
    }else if(indexPath.section == 2){
        return [self buildDeleteButtonCellForTableView:tableView atIndexPath:indexPath];
    }
    
    return nil;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        return YES;
    }else if(indexPath.section == 2){
        UITableViewCell *deleteCell = [self.tableView cellForRowAtIndexPath:indexPath];
        UIButton *deleteButton = (UIButton *)[deleteCell viewWithTag:2];
        if(self.tableView.editing == YES){
            [deleteButton setHidden:NO];
        }else{
            [deleteButton setHidden:YES];
        }
        return NO;
    }
    return NO;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; 
    return [UITableView createSectionHeaderTextLabel:sectionTitle];
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        Plant *plantToDelete = [self.plantArray objectAtIndex:indexPath.row];
        [self.bed removePlantsObject:plantToDelete];
        //Need to delete from the Mutable array aswell
        [self.plantArray removeObject:plantToDelete];
        NSMutableArray *incompsToDeleteArray = [self.bed getPlotIncompatibilitiesToDelete:plantToDelete];
        for (PlotIncompatibilty *incomp in incompsToDeleteArray) {
            [self.bed removeIncompatibilitiesObject:incomp];
        }
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}




#pragma mark - Table view delegate

/*Show an alertView when the bug image is tapped. Offering the user a chance to ignore the incompatibility or fix it*/
-(void) bugTapped:(UITapGestureRecognizer *)sender
{
    UIButton *tappedButton = (UIButton *)sender.view;
    self.selectedIncompatible = [self.incompatibles objectAtIndex:tappedButton.tag -32];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Compatibility Issue" 
                                                    message:[NSString stringWithFormat:@"%@ is not compatible with %@", self.selectedIncompatible.plant1, self.selectedIncompatible.plant2] 
                                                   delegate:self 
                                          cancelButtonTitle:@"Ignore" 
                                          otherButtonTitles:@"Fix it!", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Fix it!"]){
        NSLog(@"Fixing it");
        [self.tableView setEditing:YES animated:YES];
        //Need to set this so that the rightBarButtonItem changes to "Done"
        [self setEditing:YES animated:YES];
        //self.navigationItem.rightBarButtonItem. = UIBarButtonSystemItemDone;
    }else if([title isEqualToString:@"Ignore"]){
        NSLog(@"Ignoring it");
        PlotIncompatibilty *incomp = [PlotIncompatibilty selectPlotIncompatibilityByPlant1Name:self.selectedIncompatible.plant1 
                                                                                 andPlant2Name:self.selectedIncompatible.plant2 
                                                                                    andBedName:self.bed.name 
                                                                                   withContext:self.bed.managedObjectContext];
        incomp.alertUser = [NSNumber numberWithBool:NO];
        [self.tableView reloadData];
        [self.tableView setNeedsDisplay];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"viewSuggestedCompanions"]){
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        SuggestedCompanionsTableViewController *suggestedCompanionsVC = [navCon.viewControllers objectAtIndex:0];
        [suggestedCompanionsVC setPlants:[NSArray arrayWithArray:self.plantArray]];
        [suggestedCompanionsVC setDelegate:self];
    }
}

- (IBAction)viewSuggestedCompanionsPressed:(UIButton *)sender 
{
    [self performSegueWithIdentifier:@"viewSuggestedCompanions" sender:sender];
}

#pragma mark - SelectCompanionPlantsDelegate

/*Implementation of the delegate method to handle the addition of new suggested companion plants*/
-(void)suggestedCompanionPlantsSelected:(NSArray *)plants
{
    for (Plant *suggestedCompanion in plants) {
        [self.bed addPlantsObject:suggestedCompanion];
    }
    [self.tableView reloadData];
}
@end
